package com.lu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.reggie.common.BaseContext;
import com.lu.reggie.entity.*;
import com.lu.reggie.exceptions.BusinessException;
import com.lu.reggie.mapper.OrdersMapper;
import com.lu.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 况山云
 * @since 2022-08-22
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private IShoppingCartService iShoppingCartService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IAddressBookService iAddressBookService;
    @Autowired
    private IOrderDetailService iOrderDetailService;
    /**
     * 用户下单自定义
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //主要就是根据用户Id
        Long userId = BaseContext.getCurrentId();
        //查询该用户1的购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = iShoppingCartService.list(queryWrapper);
        //判断是否为空
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new BusinessException("购物车不能为空!");
        }
        //再去查询用户数据
        User user = iUserService.getById(userId);
        //查询该用户的的地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = iAddressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new BusinessException("用户地址不能为空!");
        }
        //设置该用户的订单号
        long orderId = IdWorker.getId();
        AtomicInteger atomicInteger = new AtomicInteger(0);
        //设置订单明细的属性数据
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //设置order表属性数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(atomicInteger.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //插入一条数据到order
        this.save(orders);
        //订单明细表插入所有
        iOrderDetailService.saveBatch(orderDetails);

        //最后清空购物车
        iShoppingCartService.remove(queryWrapper);
    }
}
